function validateAddPositionForm() {
	if (document.add_position_form.elements[0].value == '') {
		alert("No product is selected");
		return false;
	}
	str = document.add_position_form.elements[1].value;
	if (str.match(/^[0-9]+(\.[0-9]+)?$/ )) {
		return true;
	} else {
		alert("Quantity must be a decimal value");
		return false;
	}
}

function addPosition(positions, indexKey, id, name, quantity, unit) {
	positions.push(new Array(indexKey, id, quantity));
	createPositionHTML(indexKey, id, name, quantity, unit);
}

function addPositionFromForm(positions, indexKey) {
	positions.push(new Array(indexKey, document.add_position_form.elements[0].value, document.add_position_form.elements[1].value));
	var selectedIndex = document.add_position_form.elements[0].selectedIndex;
	var id = document.add_position_form.elements[0].options[selectedIndex].value;
	var name = document.add_position_form.elements[0].options[selectedIndex].text;
	var quantity = document.add_position_form.elements[1].value;
	var unit = document.getElementById("unit_field").innerHTML;
	createPositionHTML(indexKey, id, name, quantity, unit);
}

function createPositionHTML(indexKey, id, name, quantity, unit) {
	var positionId = "position_" + indexKey;
	document.getElementById("positions_list").innerHTML += '<li id="' + positionId + '"><a href = /products/' + id + '>'
	  + name + '</a> - ' + quantity + ' ' + unit + ' | '
	  + '<a href="#" onclick="removePositionHTML(' + indexKey + '); removePosition(positions, ' + indexKey + ');">Remove</a></li>';
}

function removePositionHTML(indexKey) {
	var positionId = "position_" + indexKey;
	var childNode = document.getElementById(positionId)
	document.getElementById("positions_list").removeChild(childNode);
}

function removePosition(positions, indexKey) {
	for (var i = 0; i < positions.length; i++) {
		var position = positions.shift();
		if (position[0] != indexKey) {
			positions.push(position);
		}
	}
	positions.reverse();
}

function removeAllPositions(positions) {
	positions = new Array();
	document.getElementById('positions_list').innerHTML = '';
}

function setUnitField(productUnitsMap) {
	var selectedIndex = document.add_position_form.elements[0].selectedIndex;
	var unit = productUnitsMap[document.add_position_form.elements[0].options[selectedIndex].value];
	if (unit) {
		document.getElementById("unit_field").innerHTML = unit;
	} else {
		document.getElementById("unit_field").innerHTML = '';
	}
}

function setPositionsCookie(positions) {
	var valueString = new String();
	for (var i = 0; i < positions.length; i++) {
		var position = positions[i];
		valueString += position[1] + "_" + position[2] + ",";
	}
    var exDate = new Date();
	exDate.setHours(exDate.getHours() + 1);
	var cookieString = 'positions=' + escape(valueString) + ';expires=' + exDate.toGMTString() + ";path=/"
	document.cookie = cookieString;
}
